package com.fsds.crem.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fsds.crem.web.entity.AccountInfo;
import com.fsds.crem.web.service.ReportEmailService;

@Controller
@RequestMapping("/report/email/")
public class ReportEmailController {

	private Logger logger = Logger.getLogger(ReportEmailController.class);
	
	@Resource
	private ReportEmailService reportEmailService;
	 
	
	/**
	 * 收件人设定页面跳转
	 * 
	 * @param request
	 * @param reportType
	 * @return
	 */
	@RequestMapping(value="/setAddress")
	public String setAddress(HttpServletRequest request,String reportType){

		// 报表类型不为空时，获取可选收件人和已选收件人
		if(StringUtils.isNotEmpty(reportType)){
			
			// 可选收件人
			List<AccountInfo> newList = reportEmailService.findByNoInstalled(reportType);
			request.setAttribute("newList", newList);
			
			// 已选收件人
			List<AccountInfo> oldList = reportEmailService.findByInstalled(reportType);
			
			// 默认设置的收件人
			StringBuilder defaultValue = new StringBuilder();
			for(AccountInfo a : oldList){
				defaultValue.append(a.getEmpNo()).append(",");
			}
			request.setAttribute("oldList", oldList);
			request.setAttribute("defaultValue", defaultValue);
		}
		
		return "reportemail/setaddress";
	}
	
	/**
	 * 保存报表设置的收件人
	 * 
	 * @param request
	 * @param response
	 * @param reportType
	 * @param empNo
	 * @return
	 */
	@RequestMapping(value="/saveAddress")
	@ResponseBody
	public String saveAddress(HttpServletRequest request,HttpServletResponse response,
							String reportType,String empNo){
		JSONObject json = new JSONObject();
		try {
			
			reportEmailService.saveAddress(reportType, empNo);
			json.put("result", "success");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			json.put("result", "error");
		} 
		
		return json.toString();
	}
}
